package com.example.javaow.service.impl;



import com.example.javaow.config.JwtUtil;
import com.example.javaow.domain.base.ResponseResult;
import com.example.javaow.domain.dto.Login;
import com.example.javaow.domain.dto.RegisterDTO;
import com.example.javaow.domain.entity.User;
import com.example.javaow.mapper.UserMapper;
import com.example.javaow.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@Service
public class UserServiceImpl implements UserService, UserDetailsService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // ❌ 删除了 @Autowired private UserDetailsService userDetailsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
        );
    }

    @Override
    public ResponseResult<Map<String, Object>> login(Login login) {
        try {
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword())
            );

            // ✅ 改成调用自己
            UserDetails userDetails = loadUserByUsername(login.getUsername());
            String token = jwtUtil.generateToken(userDetails.getUsername());

            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            return ResponseResult.success(data);

        } catch (Exception e) {
            return ResponseResult.error("用户名或密码错误");
        }
    }

    @Override
    public ResponseResult<String> register(RegisterDTO registerDTO) {
        User existingUser = userMapper.selectByUsername(registerDTO.getUsername());
        if (existingUser != null) {
            return ResponseResult.error("用户名已存在");
        }

        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setNickname(registerDTO.getNickname());
        user.setStatus("InOffice");

        int result = userMapper.insert(user);
        if (result > 0) {
            return ResponseResult.success("注册成功");
        } else {
            return ResponseResult.error("注册失败，请重试");
        }
    }
}